from django.shortcuts import render
from rest_framework import generics, mixins
from rest_framework.decorators import api_view
from userAccount import serializers, models
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from userAccount.functions import tools
from userAccount.functions import dbs
from MC import settings
from userAccount.functions.tools import response_origin
from django.db import transaction
import json
from django.db.models import Q, F
import time, datetime
import re
import os
import requests
from sso.views import login_authen


# Create your views here.

@api_view(http_method_names=['GET'])
def health(data):
    content = {}
    data = {'status': 'UP'}
    content['payload'] = {"data", json.dumps(data)}
    content['status'] = 1
    content['errmsg'] = ""
    return Response(data)


@api_view(http_method_names=['GET'])
# @login_authen
# def user_db(request, args, auth):
def user_db(request, uid):
    """
    获取此用戶所在的數據庫
    """
    if request.method == "GET":
        try:
            # uid = args[0].split("/")[0]
            uid = uid.split("/")[0]
            tenobj = models.TEnterpriseCertification.objects.filter(f_account=uid)
            if not tenobj:
                content = tools.make_false_dict()
                content["errmsg"] = "无此用户数据"
                return response_origin(content)
            tenant_id = models.TEnterpriseCertification.objects.get(f_account=uid).f_enterprise_certification_id
            data = models.TEnterpriseData.objects.filter(id=tenant_id).values('database_type', "tenant_id", "db_name")
            content = tools.make_standard_dict()
            content["payload"] = data
            return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content['errmsg'] = str(e)
            return Response(content)


class UserRegistersView(generics.ListCreateAPIView):
    # queryset = models.TbUser.objects.all()
    serializer_class = serializers.UserSerializer

    def get_queryset(self):
        pass

    def get(self, request, *args, **kwargs):
        return Response({"message": "请输入信息"})

    def post(self, request, *args, **kwargs):
        """
        用户注册接口
        参数必填
        :param request:
        nickname 用戶暱稱
        phone 手機號碼
        password 密碼
        code 驗證碼
        :return:
        """
        content = tools.make_standard_dict()
        serializer = serializers.UserSerializer(data=request.data)
        try:
            if serializer.is_valid():
                data = dict(serializer.validated_data)
                code_s = tools.check_phone(data["phone"], data["code"])  # 校准验证码
                if not code_s["status"] == 0:  # 如果验证码不正确，则返回相应内容
                    content = tools.make_false_dict()
                    content["errmsg"] = code_s["errmsg"]
                    return response_origin(content)
                uid = tools.only_num()
                reg_time = int(round(time.time() * 1000))  # 注册时间，转化为13位时间戳
                with transaction.atomic():
                    user = models.TUserInfo()
                    user.f_nickname = data["nickname"]
                    user.f_passwd = tools.hash_password(data["password"])
                    user.f_mobile_phone = data["phone"]
                    user.f_account = uid
                    user.f_registration_time = reg_time
                    user.f_consent_statement = 1
                    user.f_personal_authentication_state = 0
                    user.f_enterprise_certification_state = 0
                    user.save()

                content['payload']["message"] = "新用户注册成功！"
                content["payload"]["nickname"] = data["nickname"]
                return response_origin(content)
            else:
                content = tools.make_false_dict()
                content['errmsg'] = serializer.errors
        except Exception as e:
            content = tools.make_false_dict()
            content['errmsg'] = str(e)
        finally:
            return response_origin(content)


class LoginView(generics.ListCreateAPIView):
    queryset = models.TUserInfo.objects.all()
    serializer_class = serializers.LoginSerializer

    def get(self, request, *args, **kwargs):
        return response_origin({"message": "請輸入用戶名或密碼!"},
                               status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        """
        用户登录接口
        :param request: POST
        :param args:
        phone 手机号
        password 用户密码
        :param kwargs:
        :return:
        """
        try:
            content = tools.make_standard_dict()
            data = tools.is_data(request, "POST", "phone", "password")
            # print(data)
            if not isinstance(data, dict):
                return data

            userobj = models.TUserInfo.objects.filter(f_mobile_phone=data["phone"])
            if not userobj:
                content["errmsg"] = "用戶'%s'不存在！" % data["phone"]
                content["status"] = 1
                return Response(content)
            if tools.hash_password(data["password"]) == userobj.values("f_passwd")[0]["f_passwd"]:
                user = models.TUserInfo.objects.get(f_mobile_phone=data["phone"])
                content["payload"] = {"account": user.f_account, "nickname": user.f_nickname,
                                      "reg_time": time.strftime('%Y-%m-%d %H:%M:%S',
                                                                time.localtime(user.f_registration_time / 1000)),
                                      "password": user.f_passwd, "email": user.f_email, "avatar": user.f_picture,
                                      "company_name": user.f_company_name, "job": user.f_job_titles,
                                      "user_address": user.f_contact_address, "company_mobile": user.f_company_phone,
                                      "company_fax": user.f_company_fax,
                                      "is_authentication_state": user.f_personal_authentication_state,
                                      "is_enterprise_state": user.f_enterprise_certification_state}
                return response_origin(content)
            else:
                content["errmsg"] = "密码错误"
                content["status"] = 1
                return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content['errmsg'] = str(e)
            return response_origin(content)


class UserDetailView(generics.ListCreateAPIView):
    """
    GET提供參數:
    搜索值search，搜索字段範圍fields(數組類型, 默認參數為"['username']")，\n
    搜索方式是否為模糊搜索vague(布爾類型, 默認為False) \n
    可選參數page(頁碼,默認值為1) \n
    page_num(每頁的數量, 默認值為10)

    """
    queryset = models.TUserInfo.objects.all()
    serializer_class = serializers.UserDetailSerializer

    # @login_authen
    def get(self, request, *args, **kwargs):
        # org_id = request.GET.get("org_id", None)
        search = request.GET.get("search", None)
        fields = request.GET.get("fields", "['f_nickname']")
        vague = request.GET.get("vague", "False")
        page = request.GET.get("page", "1")
        page_num = request.GET.get("page_num", settings.PAGE_NUMBER)
        page = abs(int(page))
        page_num = abs(int(page_num))
        count = 0
        if search:
            try:
                if vague == "True":  # 選擇模糊搜索
                    fields = re.findall(r'\w+', fields)
                    # select = """Q({0}__icontains='{1}')""".format(fields[0], search)
                    # fields.pop(0)
                    field_dict = {}
                    for field in fields:
                        field_dict[field + "__icontains"] = search
                        count2 = models.TUserInfo.objects.filter(**field_dict).count()
                        if count2:
                            queryset = models.TUserInfo.objects.filter(**field_dict)[
                                       page_num * page - page_num:page_num * page]
                            count = count2
                        else:
                            pass
                    if not count:
                        queryset = models.TUserInfo.objects.filter(**field_dict)[
                                   page_num * page - page_num:page_num * page]
                    # select += """ | Q({0}__icontains='{1}')""".format(field, search)
                    # find_select = re.findall(r'(?:(?<=Q\(f_))\w+',select)
                    # all_select = select.split("|")
                    # if len(find_select) != len(all_select):
                    #     content = tools.make_false_dict()
                    #     content["errmsg"] = "无此查询内容"
                    #     return response_origin(content)
                    # # select = re.findall()
                    # print(select,2)
                    # count = models.TUserInfo.objects.filter(**field_dict).count()
                    # print(count)
                    # return response_origin({"hha": "123"})
                    # queryset = eval("models.TUserInfo.objects.filter({0})[{1}:{2}]".format(select,
                    #                                                                     page_num * page - page_num,
                    #                                                                     page_num * page))
                    # print(models.TUserInfo.objects.filter(**{"Q(f_nickname__icontains)":"w","Q(f_account__icontains)":"w"}))
                else:  # 選擇精確搜索  当前页码 每页多少条
                    fields = re.findall(r'\w+', fields)
                    field_dict = {}
                    for field in fields:
                        field_dict[field + "__iexact"] = search
                        count2 = models.TUserInfo.objects.filter(**field_dict).count()
                        if count2:
                            queryset = models.TUserInfo.objects.filter(**field_dict)[
                                       page_num * page - page_num:page_num * page]
                            count = count2
                        else:
                            pass
                    if count == 0:
                        queryset = models.TUserInfo.objects.filter(**field_dict)[
                                       page_num * page - page_num:page_num * page]
                    # select = """Q({0}__iexact='{1}')""".format(fields[0], search)
                    # fields.pop(0)
                    # for field in fields:
                    #     select += """ | Q({0}__iexact='{1}')""".format(field, search)
                    # find_select = re.findall(r'(?:(?<=Q\(f_))\w+', select)
                    # all_select = select.split("|")
                    # if len(find_select) != len(all_select):
                    #     content = tools.make_false_dict()
                    #     content["errmsg"] = "无此查询内容"
                    #     return response_origin(content)
                    # count = eval("models.TUserInfo.objects.filter({0}).count()".format(select))
                    # queryset = eval("models.TUserInfo.objects.filter({0})[{1}:{2}]".format(select,
                    #                                                                        page_num * page - page_num,
                    #                                                                        page_num * page))
                query_data = serializers.UserDetailSerializer(queryset, many=True).data
                if query_data:
                    return response_origin({"status": 0,
                                            "payload": serializers.UserDetailSerializer(queryset, many=True).data,
                                            "errmsg": "",
                                            "count": count})
                else:
                    content = tools.make_false_dict()
                    content["errmsg"] = "无此查询内容"
                    return response_origin(content)
            except Exception as error:
                return response_origin({"status": 1, "errmsg": str(error), "payload": []})
        else:
            queryset = models.TUserInfo.objects.all()[page_num * page - page_num:page_num * page]

            query_data = serializers.UserDetailSerializer(queryset, many=True).data
            if query_data:
                return response_origin({"status": 0,
                                        "payload": query_data,
                                        "errmsg": "",
                                        "count": models.TUserInfo.objects.all().count()})
            else:
                content = tools.make_false_dict()
                content["errmsg"] = "无此查询内容"
                return response_origin(content)


class checkView(generics.ListCreateAPIView):
    queryset = models.TUserInfo.objects.all()
    serializer_class = serializers.CheckSerializer

    def get(self, request, *args, **kwargs):
        return response_origin({"message": "請輸入账号!"},
                               status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        """
        account: 手机账号

        """
        content = tools.make_standard_dict()
        serializer = serializers.CheckSerializer(data=request.data)
        try:
            if serializer.is_valid():
                content["payload"]["message"] = "该手机号未被绑定"
                return response_origin(content)
            else:
                content["errmsg"] = serializer.errors
                return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content["errmsg"] = str(e)
            return response_origin(content)


class batchAccountView(generics.ListCreateAPIView):
    queryset = models.TUserInfo.objects.all()
    serializer_class = serializers.BatchAccountSerializer

    def get(self, request, *args, **kwargs):
        return response_origin({"message": "請輸入用戶名或密碼!"},
                               status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        content = tools.make_standard_dict()
        data = tools.is_data(request, "POST", "num", "nickname", "password")
        # print(data)
        if not isinstance(data, dict):
            return data
        try:
            if data["num"]:
                for i in range(int(data["num"])):
                    uid = tools.only_num()
                    reg_time = int(round(time.time() * 1000))  # 注册时间，转化为13位时间戳
                    with transaction.atomic():
                        user = models.TUserInfo()
                        user.f_nickname = data["nickname"] + str(i + 1)
                        user.f_passwd = tools.hash_password(data["password"])
                        user.f_mobile_phone = tools.verify_code()
                        user.f_account = uid[:-len(str(i))] + str(i)  # "2"+str(i+1).zfill(10)
                        user.f_registration_time = reg_time
                        user.f_consent_statement = 1
                        user.f_personal_authentication_state = 0
                        user.f_enterprise_certification_state = 0
                        user.save()
                content["payload"]["message"] = "success"
                return response_origin(content)
        except Exception as e:
            content = tools.make_false_dict()
            content["errmsg"] = str(e)
            return response_origin(content)
